package enhance.plus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import enhance.plus.logic.LogicBaseField;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

public class LogicMetaObjectHandler implements MetaObjectHandler {

	private LogicMetaObjectHandlerService logicMetaObjectHandlerService;

	public LogicMetaObjectHandler(LogicMetaObjectHandlerService logicMetaObjectHandlerService) {
		super();
		this.logicMetaObjectHandlerService = logicMetaObjectHandlerService;
	}

	/**
	 * 新增表数据时需要添加的数据
	 *
	 * @param metaObject
	 */
	@Override
	public void insertFill(MetaObject metaObject) {
		Object createTime = getFieldValByName(LogicBaseField.createTime, metaObject);
		if (null == createTime) {
			setFieldValByName(LogicBaseField.createTime, new Date(), metaObject);
		}
		Object modifyTime = getFieldValByName(LogicBaseField.lastModificationTime, metaObject);
		if (null == modifyTime) {
			setFieldValByName(LogicBaseField.lastModificationTime, new Date(), metaObject);
		}
		Object removed = getFieldValByName(LogicBaseField.removeFlag, metaObject);
		if (null == removed) {
			setFieldValByName(LogicBaseField.removeFlag, 0, metaObject);
		}
		Object createUser = getFieldValByName(LogicBaseField.createUser, metaObject);
		String operator = logicMetaObjectHandlerService.getOperator();
		if(null == createUser) {
			setFieldValByName(LogicBaseField.createUser, operator , metaObject);
		}
	}


	/**
	 * 表数据更新时需要自动修改的数据
	 *
	 * @param metaObject
	 */
	@Override
	public void updateFill(MetaObject metaObject) {
		Object modifyTime = getFieldValByName(LogicBaseField.lastModificationTime, metaObject);
		if (null == modifyTime) {
			setFieldValByName(LogicBaseField.lastModificationTime, new Date(), metaObject);
		}
	}

}
